package com.testingedu.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * connection管理类
 * @author lsww
 * @E-mail lsww90@Gmail.com
 * @createtime 2013-1-29 下午04:38:53
 * @version 1.0
 * @since JDK 1.6
 */
public class DBManager {
	private static final Log log = LogFactory.getLog(DBManager.class);
	private static final String configFile = "c3p0.properties";
	private static DataSource dataSource;
	static {
		initDataSource();
	}
	/**
	 * 初始化数据源
	 */
	private static final void initDataSource() {
		Properties dbProperties = new Properties();
		try {
			dbProperties.load(DBManager.class.getClassLoader()
					.getResourceAsStream(configFile));
			Properties cpProperties = new Properties();
			for (Object key : dbProperties.keySet()) {
				String skey = (String) key;
				if (skey.startsWith("jdbc.")) {
					String name = skey.substring(5);
					cpProperties.put(name, dbProperties.getProperty(skey));
				}
			}
			dataSource = (DataSource) Class.forName(
					cpProperties.getProperty("datasource")).newInstance();
			if (dataSource.getClass().getName().indexOf("c3p0") > 0) {
//				System.setProperty(
//						"com.mchange.v2.c3p0.management.ManagementCoordinator",
//						"com.mchange.v2.c3p0.management.NullManagementCoordinator");
			}
			BeanUtils.populate(dataSource, cpProperties);
			Connection conn = getConnection();
			DatabaseMetaData mdm = conn.getMetaData();
			System.out.println("Connected to " + mdm.getDatabaseProductName() + " "
					+ mdm.getDatabaseProductVersion());
			if(conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			log.error("初始化连接池失败："+e);
		}
	}
	/**
	 * 关闭数据源
	 */
	public static final void closeDataSource() {
		try {
			dataSource.getClass().getMethod("close").invoke(dataSource);
		} catch (Exception e) {
			log.error("关闭连接池失败："+e);
		}
	}
	
	/**
	 * 获取一个新连接
	 * @return
	 */
	public static final Connection getConnection() {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			log.error("获取数据库连接失败："+e);
		}
		return conn;
	}
	
	public static void main(String[] args) {
		System.out.println(getConnection());
	}
}
